import cv2
import os
import time
from pathlib import Path

# 监控的文件夹路径
watch_folder = r"E:\University\Junior_up\twelfth_xing_huo_bei\Volume_Measure\Using Python\Photograph_Data\Initial_Photograph"
# 保存左图的文件夹路径
left_folder = r"E:\University\Junior_up\twelfth_xing_huo_bei\Volume_Measure\Using Python\Photograph_Data\Left_view"
# 保存右图的文件夹路径
right_folder = r"E:\University\Junior_up\twelfth_xing_huo_bei\Volume_Measure\Using Python\Photograph_Data\Right_View"
# 计数器文件路径
counter_file = r"E:\University\Junior_up\twelfth_xing_huo_bei\Volume_Measure\Using Python\Photograph_Data\counter.txt"

# 确保保存图片的文件夹存在
Path(left_folder).mkdir(parents=True, exist_ok=True)
Path(right_folder).mkdir(parents=True, exist_ok=True)

def get_or_init_counter(counter_file):
    """获取计数器的值，如果文件不存在则初始化为1"""
    if os.path.exists(counter_file):
        with open(counter_file, 'r') as f:
            return int(f.read().strip())
    else:
        with open(counter_file, 'w') as f:
            f.write(1)
            return 1

def update_counter(counter_file, counter):
    """更新计数器的值"""
    with open(counter_file, 'w') as f:
        f.write(str(counter))

# 获取或初始化计数器
image_counter = get_or_init_counter(counter_file)

# 监控文件夹
for filename in os.listdir(watch_folder):
    if filename.endswith(".jpg"):  # 确保是JPG文件
        file_path = os.path.join(watch_folder, filename)
        img = cv2.imread(file_path)
        if img is not None and img.shape[0] == 1080 and img.shape[1] == 3840:           ##shape[0]宽度；shape[1]长度
            # 分割图片
            imgleft = img[0:1080, 0:1920]  # 根据你的分割尺寸调整
            imgright = img[0:1080, 1920:3840]  # 根据你的分割尺寸调整
            
            # 构建保存路径
            left_save_path = os.path.join(left_folder, f"Left_Real_{image_counter}.jpg")
            right_save_path = os.path.join(right_folder, f"Right_Real_{image_counter}.jpg")
            
            # 保存图片
            cv2.imwrite(left_save_path, imgleft)
            cv2.imwrite(right_save_path, imgright)
            
            # 更新图片计数器
            image_counter += 1
            update_counter(counter_file, image_counter)
        else:
            print(f"Skipped file {filename} due to incorrect dimensions or file not found.")

print("Image processing complete.")